//
//  DiscoveryController.swift
//  发现界面
//
//  Created by jin on 2024/8/27.
//

import UIKit
import SwiftEventBus
import Alamofire

class DiscoveryController: BaseMainController {

    override func initViews() {
        super.initViews()
        
        //初始化TableView结构
        initTableViewSafeArea()
        
        //下拉刷新
        let header=MJRefreshNormalHeader {
            [weak self] in
            self?.loadData()
        }

        //隐藏标题
        header.stateLabel?.isHidden = true

        // 隐藏时间
        header.lastUpdatedTimeLabel?.isHidden = true
        tableView.mj_header=header
        
        //注册cell
        tableView.register(BannerCell.self, forCellReuseIdentifier: Constant.CELL)
        tableView.register(ButtonCell.self, forCellReuseIdentifier: ButtonCell.NAME)
        tableView.register(SheetGroupCell.self, forCellReuseIdentifier: SheetGroupCell.NAME)
        tableView.register(SongGroupCell.self, forCellReuseIdentifier: SongGroupCell.NAME)
        tableView.register(FooterCell.self, forCellReuseIdentifier: FooterCell.NAME)
    }
    
    override func initDatum() {
        super.initDatum()
        //loadData()
        startRefresh()
        
        //测试数据库使用
//        var searchHistory=SearchHistory()
//        searchHistory.title="爱学啊1"
//        searchHistory.createdAt = Int(Date().timeIntervalSince1970)
//
//        //保存
//        SuperDatabaseManager.shared.saveSearchHistory(searchHistory)
//
//        searchHistory=SearchHistory()
//        searchHistory.title="爱学啊3"
//        searchHistory.createdAt = Int(Date().timeIntervalSince1970)
//        SuperDatabaseManager.shared.saveSearchHistory(searchHistory)
//
//        //查询所有
//        var results = SuperDatabaseManager.shared.getSearchHistoryAll()
//        for it in results {
//            print("test database query \(it.title!)")
//        }
//
//        //删除第二次添加的对象
//        SuperDatabaseManager.shared.deleteSearchHistory(searchHistory)
//
//        results = SuperDatabaseManager.shared.getSearchHistoryAll()
//        for it in results {
//            print("test database query \(it.title!)")
//        }
        
//        //查询所有
//        var results = SuperDatabaseManager.shared.findPlayList()
//        for it in results {
//            print("test database query \(it.title!)")
//        }
    }
    
    func startRefresh() {
        //进入界面后自动刷新，会调用回调方法
        tableView.mj_header!.beginRefreshing()
    }
    
    func endRefresh()  {
        tableView.mj_header!.endRefreshing()
    }
    
    func loadData() {
        DefaultRepository.shared.bannerAds().subscribeSuccess { [weak self] data in
            //清除原来的数据
            self?.datum.removeAll()
            
            //添加轮播图
            self?.datum.append(BannerData(data:data.data!.data!))
            
            //添加快捷按钮
            self?.datum.append(ButtonData())
            
            //请求歌单数据
            self?.loadSheetsData()
        }.disposed(by: rx.disposeBag)
    }
    
    /// 请求歌单数据
    func loadSheetsData() {
        DefaultRepository.shared.sheets(size: VALUE12).subscribeSuccess { [weak self] data in
            //添加歌单数据
            self?.datum.append(SheetData(data.data!.data!))
            
            // 请求音乐数据
            self?.loadSongsData()
        }.disposed(by: rx.disposeBag)
    }
    
    /// 请求音乐数据
    func loadSongsData() {
        DefaultRepository.shared.songs().subscribeSuccess { [weak self] data in
            self?.endRefresh()
            
            //添加音乐数据
            self?.datum.append(SongData(data.data!.data!))
            
            //添加尾部数据
            self?.datum.append(FooterData())
            
            self?.tableView.reloadData()
            
            //请求启动界面广告，当然也可以和轮播图接口一起返回
            self?.loadSplashAd()
        }.disposed(by: rx.disposeBag)
    }
    
    func loadSplashAd() {
        DefaultRepository.shared
            .splashAds()
            .subscribe {[weak self] data in
                self?.processSplashAd(data.data.data ?? [])
            } _: { data, error in
                
                return true
            }.disposed(by: rx.disposeBag)

    }
    
    func processSplashAd(_ data:[Ad]) {
        if data.count > 0 {
            prepareDownloadAd(data[0])
        } else {
            //删除本地广告数据
            
            //获取广告信息,TODO 这样只能删除上一个广告,但没法删除全部,可以优化
            if let _ = PreferenceUtil.getSplashAd() {
                //删除配置文件
                PreferenceUtil.setSplashAd(nil)
                
                //删除文件
            }
        }
    }
    
    func prepareDownloadAd(_ data:Ad) {
        //保存
        PreferenceUtil.setSplashAd(data)
        
        //判断文件是否存在，如果存在就不下载
        let path=StorageUtil.adPath(data.icon)
        if SuperFileUtil.exists(path.path) {
            print("ad exist,skip downloaded \(data.icon!) \(path.path)")
            return
        }
        
//        let reachability = Reachability(hostName: "www.ixuea.com")
//        let reachabilityStatus = reachability!.currentReachabilityStatus()
//        if reachabilityStatus == ReachableViaWiFi {
            SuperFileUtil.mkdirs(path.deletingLastPathComponent().path)
            
            //wifi
            downloadAd(data,path)
       // }
    }
    
    func downloadAd(_ data:Ad,_ path:URL) {
        let destination: DownloadRequest.Destination = { _, _ in
            return (path, [.removePreviousFile, .createIntermediateDirectories])
        }

        AF.download(data.icon.absoluteUri(), to: destination).response { response in
            if response.error == nil, let filePath = response.fileURL?.path {
                print("ad downloaded success \(filePath)")
            }
        }
    }
    
    override func initListeners() {
        super.initListeners()
        //监听单曲点击事件
        SwiftEventBus.onMainThread(self, name : Constant.EVENT_SONG_CLICK) {[weak self] data in
            self?.processSongClick(data?.object as! Song)
        }
        
        //点击事件，根据style区分具体是什么点击
        SwiftEventBus.onMainThread(self, name : Constant.CLICK_EVENT) { [weak self] sender in

            //获取发送过来的数据
            let data = sender?.object as! MyStyle

            self?.processClick(data)
        }
        
        //登录点击事件
        NotificationCenter.default.addObserver(self, selector: #selector(toLoginClick(_:)), name: NSNotification.Name(Constant.EVENT_LOGIN_CLICK), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(prepareProcessAdClick(_:)), name:NSNotification.Name(rawValue: Constant.EVENT_BANNER_CLICK), object: nil)
    }
    
    @objc func prepareProcessAdClick(_ d:Notification) {
        let data = d.userInfo![Constant.DATA] as! Ad
        processAdClick(data)
    }
    
    /// banner广告点击
    func processAdClick(_ data:Ad){
        if data.uri.starts(with: "http") {
            print("processAdClick \(navigationController)")
            SuperWebController.start(navigationController!,title: data.title,uri: data.uri)
        }
    }
    
    /// 单曲点击
    /// - Parameter data: <#data description#>
    func processSongClick(_ data:Song) {
        MusicListManager.shared().setDatum([data])
        MusicListManager.shared().play(data)
        startMusicPlayerController()
    }
    
    @objc func toLoginClick(_ data:Notification) {
        toLogin()
    }
    
    func processClick(_ data:MyStyle) {
        switch data {
        case .refresh:
            //底部刷新
            autoRefresh()
        default:
            break
        }
    }
    
    func autoRefresh() {
        //滚动到顶部
        let indexPath = IndexPath(item: 0, section: 0)
        tableView.scrollToRow(at: indexPath, at: .top, animated: true)
        
        //延时300毫秒，执行加载数据，目的是让列表先向上滚动到顶部
        DispatchQueue.main.asyncAfter(deadline: .now()+0.3) {[weak self] in
            self?.startRefresh()
        }
    }
    
    /// 获取列表类型
    func typeForItemAtData(_ data : Any) -> MyStyle  {
        if data is ButtonData{
            return .button
        } else if data is SheetData{
            return .sheet
        } else if data is SongData{
            return .song
        } else if data is FooterData{
            return .footer
        }
        return .banner
    }
}

extension DiscoveryController{
    
    // 返回当前位置cell
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    /// - Returns: <#description#>
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let data = datum[indexPath.row]
        
        //获取当前Cell的类型
        let type = typeForItemAtData(data)
        
        switch(type){
        case .button:
            //按钮
            let cell = tableView.dequeueReusableCell(withIdentifier:  ButtonCell.NAME, for: indexPath) as! ButtonCell
            cell.bind(data as! ButtonData)
            return cell
        case .sheet:
            //歌单
            let cell = tableView.dequeueReusableCell(withIdentifier:  SheetGroupCell.NAME, for: indexPath) as! SheetGroupCell
            cell.delegate = self
            cell.bind(data as! SheetData)
            return cell
        case .song:
            //音乐
            let cell = tableView.dequeueReusableCell(withIdentifier:  SongGroupCell.NAME, for: indexPath) as! SongGroupCell
            cell.bind(data as! SongData)
            return cell
        case .footer:
            //底部
            let cell = tableView.dequeueReusableCell(withIdentifier:  FooterCell.NAME, for: indexPath)
            return cell
        default:
            //banner
            
            //取出一个Cell
            let cell = tableView.dequeueReusableCell(withIdentifier:  Constant.CELL, for: indexPath) as! BannerCell
            
            //绑定数据
            cell.bind(data as! BannerData)
            
            cell.bannerClick = {[weak self] data in
                self?.processAdClick(data)
            }

            return cell
        }
    }
}

extension DiscoveryController:SheetGroupDelegate{
    func sheetCLick(data: Sheet) {
        SheetDetailController.start(navigationController!, data.id)
    }
}
